/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package org.remisharrock.jcoffrefort.login;

import java.beans.PropertyChangeListener;
import java.beans.PropertyChangeSupport;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.cookie.Cookie;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.openide.util.Exceptions;
import org.openide.windows.InputOutput;

/**
 *
 * @author sharrock
 */
public class LoginManager {
    private Logger l = Logger.getLogger(Logger.GLOBAL_LOGGER_NAME);
    private String identifier;
    private String decodedpassword = "";

    public LoginManager(String identifier, char[] password) {
        this.identifier = identifier;
        for (int i = 0; i < password.length; i++) {
            decodedpassword += password[i];
        }
    }

    private String getP() {

        String P = null;

        DefaultHttpClient httpclient0 = new DefaultHttpClient();
        try {

            HttpPost httpost0 = new HttpPost("https://www.e-coffrefort.fr/memo/logon.php");
            ResponseHandler<String> responseHandler = new BasicResponseHandler();

            List<NameValuePair> nvps0 = new ArrayList<NameValuePair>();
            nvps0.add(new BasicNameValuePair("PART_ID", "MEMO"));
            nvps0.add(new BasicNameValuePair("RTNPAGE", "http://www.e-coffrefort.fr"));
            nvps0.add(new BasicNameValuePair("WIDTH", "1024"));
            nvps0.add(new BasicNameValuePair("HEIGHT", "768"));
            nvps0.add(new BasicNameValuePair("LOGON", identifier));
            nvps0.add(new BasicNameValuePair("PASSWD", decodedpassword));

            httpost0.setEntity(new UrlEncodedFormEntity(nvps0, HTTP.UTF_8));
            l.info("executing request: "+ httpost0.getURI());
            String response0 = httpclient0.execute(httpost0, responseHandler);

            l.fine("reading response: "+ response0);

            Document doc = Jsoup.parse(response0);
            Elements inputs = doc.getElementsByTag("input");
            for (Element link : inputs) {
                String value = link.attr("value");
                if (link.attr("name").equals("P")) {
                    P = value;
                    l.info(" session ID (P field): "+ P);
                }
            }

        } catch (IOException ex) {
            Exceptions.printStackTrace(ex);
        } finally {
            // When HttpClient instance is no longer needed,
            // shut down the connection manager to ensure
            // immediate deallocation of all system resources
            httpclient0.getConnectionManager().shutdown();
        }
        httpclient0.getConnectionManager().shutdown();
        return P;
    }

    public void connect() {


        /* setcookies*/

        DefaultHttpClient httpclient = new DefaultHttpClient();
        try {


            HttpPost httpost = new HttpPost("https://www.e-coffrefort.fr/memo/logon1.php");
            // ResponseHandler<String> responseHandler = new BasicResponseHandler();

            List<NameValuePair> nvps = new ArrayList<NameValuePair>();
            nvps.add(new BasicNameValuePair("P", getP()));
            nvps.add(new BasicNameValuePair("PART_ID", "MEMO"));
            nvps.add(new BasicNameValuePair("RTNPAGE", "http://www.e-coffrefort.fr"));
            nvps.add(new BasicNameValuePair("WIDTH", "1024"));
            nvps.add(new BasicNameValuePair("HEIGHT", "768"));
            nvps.add(new BasicNameValuePair("LOGON", identifier));
            nvps.add(new BasicNameValuePair("PASSWD", decodedpassword));

            httpost.setEntity(new UrlEncodedFormEntity(nvps, HTTP.UTF_8));
            l.info("executing request " + httpost.getURI());
            HttpResponse response = httpclient.execute(httpost);

            //l.info("reading response... " + response);

            HttpEntity entity = response.getEntity();

            l.info("Status : " + response.getStatusLine());
            EntityUtils.consume(entity);

            l.info("Post logon cookies");
            List<Cookie> cookies = httpclient.getCookieStore().getCookies();
            if (cookies.isEmpty()) {
                l.info("None");
            } else {
                for (int i = 0; i < cookies.size(); i++) {
                    l.fine("- " + cookies.get(i).toString());
                }
            }

            /*Listing des dossiers*/
            
            HttpGet httpget = new HttpGet("https://www.e-coffrefort.fr/memo/menuarbo.php");
             ResponseHandler<String> responseHandler = new BasicResponseHandler();
             
             l.info("executing request " + httpget.getURI());
            String response2 = httpclient.execute(httpget, responseHandler);

            l.fine("reading response... " + response2);
            String[] strLines = response2.split("\n");
             for (int i=0;i<strLines.length;i++) {
                if (strLines[i].startsWith("d.add(")) {
                    String[] split = strLines[i].split(",");
                    if (split.length >= 4) {
                        Document parse = Jsoup.parse(split[2].replace('"', ' ').trim());
                        l.info(parse.text());
                        String trim = split[3].replace('"', ' ').trim();
                        String[] split1 = trim.split("XDIR=");
                        if (split1.length >= 2) {
                            l.info("   "+split1[1]);
                        }
                    }
                }
            }
            
        } catch (IOException ex) {
            Exceptions.printStackTrace(ex);
        } finally {
            // When HttpClient instance is no longer needed,
            // shut down the connection manager to ensure
            // immediate deallocation of all system resources
            httpclient.getConnectionManager().shutdown();
        }


    }
}
